#ifndef __READWAREHOUSE_H__
#define __READWAREHOUSE_H__

#include "BaseTypeDefin.h"
#include "Dictionary.h"
#include "NumberAndWord.h"
#include "myExceptions.h"

#include <iostream>
#include <fstream>
#include <string>


class IReadWarehouse
{
public:
	virtual Dictionary* getDictionary() const = 0;
	virtual ~IReadWarehouse(){};
};

class ReadWarehouse : public IReadWarehouse
{
public:
	ReadWarehouse(const string& pPath):mDict( new Dictionary() )
	{
		readFile(pPath);
	}
	
	virtual ~ReadWarehouse()
	{};

	virtual Dictionary* getDictionary() const
	{
		return mDict;
	}
private:
	void readFile(const string& pPath)
	{
		wstring bufLine;
		typedef basic_ifstream<wchar_t, char_traits<wchar_t> > ifwstream;
		
		ifwstream file;
		try
		{
			file.open( pPath.c_str() );
		}
		catch ( ... )
		{
			cout << "bad" << endl;
		}
		
		if ( file.is_open() )
		{
			file.imbue( locale( "Russian_Russia" ) );
			int countLine = 1;
			while ( getline(file, bufLine ) ) 
			{
				if ( !parseLine(bufLine) )
				{
					logParserError.push_back(countLine);
				}
				++countLine;
			}
			file.close();
		}
		else
			throw CantOpenDict();

	};

	bool parseLine(wstring pLine)
	{
		wstring pTranslate,pValue, pRank;
		parseValue( pLine, L"value", pValue);
		parseValue( pLine, L"rank", pRank);
		parseValue( pLine, L"translate", pTranslate);
		
		if ( !pValue.empty() && !pRank.empty() && !pTranslate.empty() )
		{
			mDict->add( new myNumberAndWord(WStringTo<long>(pValue), WStringTo<int>(pRank), pTranslate ) );
			return true;
		}
		return false;
	};
	bool parseValue(wstring& pLine, wstring pName, wstring& pValue)
	{
		if ( !pLine.empty() && pLine.find( pName ) != wstring::npos )
		{
			pName+=L"=";	
			pValue = pLine.substr( pName.size(), pLine.find(L",") - pName.size() );
		
			pLine = pLine.substr(pLine.find(L",") + 1);
			return true;
		}
		return false;
	};
	Dictionary* mDict;
	vector<int> logParserError;
};

#endif __READWAREHOUSE_H__